package com.xrui.hbaseview.hbase;

import com.xrui.hbaseview.config.ConnectionDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConnectionManager implements Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(ConnectionManager.class);
    private static final Object lock = new Object();
    private static ConnectionManager instance;
    private static Map<ConnectionDetails, Connection> connections;

    private ConnectionManager() {
        connections = new HashMap<>();
    }

    public static ConnectionManager get() throws RuntimeException {
        if (instance == null) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new ConnectionManager();
                }
            }
        }

        return instance;
    }

    public Connection create(ConnectionDetails details) throws IOException {
        Connection connection = connections.get(details);
        if (connection == null) {
            LOG.debug("Cache miss for HBase connection");
            connection = new Connection(details);
            connections.put(details, connection);
        } else {
            LOG.debug("Cache hit for HBase connection");
        }
        return connection;
    }

    public void release(ConnectionDetails details) {
        connections.remove(details);
    }

    @Override
    public void close() throws IOException {
        for (Connection connection : connections.values()) {
            connection.close();
        }
        connections.clear();
    }
}
